// Browser Action 
var scriptContent = "window.xiamiFlag = 1;"; // 设定一个标志，如果有这个标志，说明这个虾米页面是自动签到插件建立的，然后再开始剩余逻辑

var createXiaMiTab = function() {
	chrome.history.deleteUrl({"url": "http://www.xiami.com"} );
	chrome.tabs.create({"url": "http://www.xiami.com", "selected": false}, function(tab) {
		localStorage["tabId"] = tab.id;
		chrome.tabs.executeScript(tab.id, {code: scriptContent}); // 进入tab执行脚本
	});
}

var signMethod = function(){
	try{
		var tabId = localStorage["tabId"];
		if (tabId != null) {
	 		chrome.tabs.get(parseInt(tabId), function(tab) {
				if (tab) return;
				createXiaMiTab();
			});
		} else {
			createXiaMiTab();
		}
	} catch (ex) {
		alert(ex.message); // 如果出错，就显示出来
	}
};

var autoSign = function(time) {
	signMethod();
	var tId = window.setInterval(function () {
		signMethod();
	}, time); 
	localStorage["timeId"] = tId;
}

var stopLoop = function(id) {
	window.clearInterval(id);
}

// ------------------------------Background context script -----------------------------------------
chrome.extension.onRequest.addListener(function(request, sender, sendResponse){
	if (sender.tab && request.stopLoop) {
		stopLoop(localStorage["timeId"]);
	} 
});
